package beer.coder.walawala.gui.component;

import beer.coder.walawala.common.constant.Constant;
import beer.coder.walawala.gui.util.StageUtil;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.Consumer;
import javafx.application.Platform;
import javafx.stage.Stage;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.plaf.basic.BasicPopupMenuUI;

/**
 * TODO
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-10-26 21:05
 */
public class WaSystemTray {

  Stage stage;
  WaTrayIcon icon;
  Consumer<Stage> onExit;

  public static WaSystemTray create(Stage stage, Consumer<Stage> onExit) {
    Platform.setImplicitExit(false);
    WaSystemTray tray = new WaSystemTray(stage, onExit);
    tray.init();
    return tray;
  }

  protected WaSystemTray(Stage stage, Consumer<Stage> onExit) {
    this.stage = stage;
    this.onExit = onExit;
  }

  protected void init() {
    if (SystemTray.isSupported()) {
      JPopupMenu menu = new JPopupMenu();
      menu.setUI(new BasicPopupMenuUI());

      JMenuItem itemShow = new JMenuItem("显示");
      itemShow.addActionListener((e) -> StageUtil.showStage(stage));

      JMenuItem itemExit = new JMenuItem("退出");
      itemExit.addActionListener(
          (e -> {
            if (icon != null) {
              SystemTray.getSystemTray().remove(icon);
            }
            StageUtil.exitStage(stage, onExit);
          }));

      menu.add(itemShow);
      menu.addSeparator();
      menu.add(itemExit);

      Image iconImg =
          Toolkit.getDefaultToolkit().getImage(Thread.currentThread().getContextClassLoader().getResource("icon.png"));
      icon = new WaTrayIcon(iconImg, Constant.APPNAME, menu);
      icon.addMouseListener(
          new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
              if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                StageUtil.switchStageStatus(stage);
              }
            }
          });

      try {
        SystemTray.getSystemTray().add(icon);
      } catch (AWTException e) {
      }
    }
  }
}
